package com.softeem.util;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;

/**
 * 返回统一格式数据
 */
@Data
@Slf4j
public class ResultBean<T> implements Serializable {

    /**
     * 返回数据的格式(成功返回): {
     * ”code“:"200",
     * "success":"true",
     * "data":{...},
     * "message":"操作成功!"
     * }
     * <p>
     * <p>
     * ==========================================
     * <p>
     * <p>
     * 返回数据的格式(失败返回): {
     * ”code“:"500",
     * "success":"false",
     * "data":null,
     * "message":"操作失败!"
     * }
     */

    private boolean isSuccess; // 是否成功

    private Integer code; // 状态码

    private T data; // 承载数据

    private String message; // 返回的消息

    /**
     * 私有的构造方法
     *
     * @param code
     * @param message
     * @param data
     */
    private ResultBean(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        //如果状态码为200则返回true,不为200全是false
        this.isSuccess = this.code.equals(ResultEnum.SUCCESS.getCode());
    }

    /**
     * 多级重载
     */
    private ResultBean(IResultCode resultCode, String message, T data) {
        this(resultCode.getCode(), message, data);
    }

    private ResultBean(IResultCode resultCode) {
        this(resultCode.getCode(), resultCode.getMessage(), (T) null);
    }

    private ResultBean(IResultCode resultCode, String message) {
        this(resultCode.getCode(), message, (T) null);
    }

    private ResultBean(IResultCode resultCode, T data) {
        this(resultCode.getCode(), resultCode.getMessage(), data);
    }

    public static <T> ResultBean<T> data(T data) {
        return data(ResultEnum.SUCCESS.getMessage(), (T) data);
    }

    public static <T> ResultBean<T> data(String message, T data) {
        return data(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMessage(), (T) data);
    }

    public static <T> ResultBean<T> data(Integer code, String message, T data) {
        return new ResultBean<T>(code, message, (T) data);
    }

    public static <T> ResultBean<T> success(String message) {
        return new ResultBean<T>(ResultEnum.SUCCESS.getCode(), message, (T) null);
    }

    public static <T> ResultBean<T> success(String message, T data) {
        return new ResultBean<T>(ResultEnum.SUCCESS.getCode(), message, (T) data);
    }

    public static <T> ResultBean<T> fail(String message) {
        return new ResultBean<T>(ResultEnum.ERROR_500.getCode(), message, (T) null);
    }

    public static <T> ResultBean<T> fail(String message, T data) {
        return new ResultBean<T>(ResultEnum.ERROR_500.getCode(), message, (T) data);
    }

    public static <T> ResultBean<T> fail(Integer code, String message) {
        return new ResultBean<T>(code, message, (T) null);
    }


    public static <T> ResultBean<T> status(boolean flag) {
        return flag ? success(ResultEnum.SUCCESS.getMessage()) : fail(ResultEnum.ERROR_500.getMessage());
    }

}

